/****************************************************************************
 *  QLyrics - A simple lyrics viewer.                                       *
 *  Copyright (C) 2008  hsys <hanshuiys@gmail.com>                          *
 *                                                                          *
 *  This program is free software; you can redistribute it and/or modify    *
 *  it under the terms of the GNU General Public License as published by    *
 *  the Free Software Foundation; either version 3 of the License, or       *
 *  (at your option) any later version.                                     *
 *                                                                          *
 *  This program is distributed in the hope that it will be useful,         *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU General Public License for more details.                            *
 *                                                                          *
 *  You should have received a copy of the GNU General Public License       *
 *  along with this program; if not, write to the Free Software Foundation, *
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA       *
 ****************************************************************************/

#include "configwindow.h"
#include <QList>
#include <QTextCodec>
#include <QFontDialog>
#include <QFileDialog>
#include <QColorDialog>
#include "configmanager.h"
#include "lyricspanel.h"

ConfigWindow::ConfigWindow(QWidget *parent) : QDialog(parent) {
    ui.setupUi(this);
    loadSettings();
};

void ConfigWindow::loadSettings() {
    ConfigManager* cfg = ConfigManager::getInstance();
    // general page
    ui.chkOnTop->setChecked(cfg->value("Window/OnTop", true).toBool());
    ui.chkFrameless->setChecked(cfg->value("Window/Frameless", true).toBool());
    ui.sbxOpacity->setValue(cfg->value("Window/Opacity", 80).toInt());
    ui.txtLyricsEditor->setText(cfg->value("Misc/LyricsEditor").toString());
    connect(ui.pbnLyricsEditor, SIGNAL(clicked()), SLOT(selectLyricsEditor()));

    // lryics page
    QList<QByteArray> encodingList = QTextCodec::availableCodecs();
    qSort(encodingList);
    for (int i = 0; i < encodingList.size(); ++i) {
        ui.cbxEncoding->addItem(encodingList.at(i));
        if (encodingList.at(i) == cfg->value("Lyrics/Encoding", "GBK").value<QByteArray>()) {
            ui.cbxEncoding->setCurrentIndex(i);
        };
    };
    ui.chkForceEncoding->setChecked(cfg->value("Lyrics/ForceEncoding", false).toBool());
    ui.txtDownloadDir->setText(cfg->value("Lyrics/DownloadDirectory", QString()).toString());
    connect(ui.pbnDownloadDir, SIGNAL(clicked()), SLOT(showDownloadDir()));
    connect(ui.rbnSongDirectory, SIGNAL(toggled(bool)), SLOT(slotDownloadDirChanged(bool)));
    if (ui.txtDownloadDir->text() == "") {
        ui.rbnSongDirectory->setChecked(true);
    } else {
        ui.rbnSpecificDirectory->setChecked(true);
    };
    m_lyricsFolders.setStringList(cfg->value("Lyrics/SearchPath").toStringList());
    ui.lsvSearchPath->setModel(&m_lyricsFolders);
    connect(ui.pbnAddFolder, SIGNAL(clicked()), SLOT(addSearchDir()));
    connect(ui.pbnRemoveFolder, SIGNAL(clicked()), SLOT(removeSearchDir()));

    // style page
    LyricsPainterManager* panelMgr = LyricsPainterManager::getInstance();
    for (int i = 0; i < panelMgr->size(); i++) {
        ui.cbxPanelType->addItem(panelMgr->get(i)->getName());
    };
    ui.cbxPanelType->setCurrentIndex(0);
    for (int i = 0; i < ui.cbxPanelType->count(); i++) {
        if (ui.cbxPanelType->itemText(i) == cfg->value("Style/ScrollStyle").toString())
            ui.cbxPanelType->setCurrentIndex(i);
    };

    ui.btnFont->setFont(cfg->value("Style/Font", QFont().toString()).value<QFont>());
    connect(ui.btnFont, SIGNAL(clicked()), SLOT(showFontPicker()));

    QPalette palette = ui.btnFgColor->palette();
    palette.setColor(QPalette::Button, cfg->value("Style/FgColor", Qt::darkGreen).value<QColor>());
    ui.btnFgColor->setPalette(palette);
    connect(ui.btnFgColor, SIGNAL(clicked()), SLOT(showColorPicker()));

    palette.setColor(QPalette::Button, cfg->value("Style/HighlightColor", Qt::green).value<QColor>());
    ui.btnHighColor->setPalette(palette);
    connect(ui.btnHighColor, SIGNAL(clicked()), SLOT(showColorPicker()));

    palette.setColor(QPalette::Button, cfg->value("Style/BgColor", Qt::black).value<QColor>());
    ui.btnBgColor->setPalette(palette);
    connect(ui.btnBgColor, SIGNAL(clicked()), SLOT(showColorPicker()));

    ui.chkFading->setChecked(cfg->value("Style/EnableFading", true).toBool());
};

template<typename T>
void ConfigWindow::testConfig(const QString& key, const T& defValue,
    const T& newValue, bool& setFlag) {
    ConfigManager* cfg = ConfigManager::getInstance();
    if (newValue != cfg->value(key, defValue)) {
        cfg->setValue(key, newValue);
        setFlag = true;
    };
};

void ConfigWindow::accept() {
    bool reloadWindow = false, reloadPanel = false, reloadLyrics = false, reloadNothing;
    // general page
    testConfig("Window/OnTop", true, ui.chkOnTop->isChecked(), reloadWindow);
    testConfig("Window/Frameless", true, ui.chkFrameless->isChecked(), reloadWindow);
    testConfig("Window/Opacity", 80, ui.sbxOpacity->value(), reloadWindow);
    testConfig("Misc/LyricsEditor", QString(), ui.txtLyricsEditor->text(), reloadNothing);

    // lryics page
    testConfig("Lyrics/Encoding", QString("GBK"), ui.cbxEncoding->currentText(), reloadLyrics);
    testConfig("Lyrics/ForceEncoding", false, ui.chkForceEncoding->isChecked(), reloadLyrics);
    testConfig("Lyrics/DownloadDirectory", QString(), ui.txtDownloadDir->text(), reloadNothing);
    testConfig("Lyrics/SearchPath", QStringList(), m_lyricsFolders.stringList(), reloadNothing);

    // style page
    testConfig("Style/ScrollStyle", QString(), ui.cbxPanelType->currentText(), reloadPanel);
    testConfig("Style/Font", QFont().toString(), ui.btnFont->font().toString(), reloadPanel);
    testConfig("Style/FgColor", QColor(Qt::darkGreen), ui.btnFgColor->palette().color(QPalette::Button), reloadPanel);
    testConfig("Style/HighlightColor", QColor(Qt::green), ui.btnHighColor->palette().color(QPalette::Button), reloadPanel);
    testConfig("Style/BgColor", QColor(Qt::black), ui.btnBgColor->palette().color(QPalette::Button), reloadPanel);
    testConfig("Style/EnableFading", true, ui.chkFading->isChecked(), reloadPanel);

    if (reloadPanel)
        emit signalReloadPanel();
    if (reloadWindow)
        emit signalReloadWindow();
    if (reloadLyrics)
        emit signalReloadLyrics();
    QDialog::accept();
};

void ConfigWindow::showFontPicker() {
    bool ok;
    QFont f = ui.btnFont->font();
    f = QFontDialog::getFont(&ok, f, this);
    if (ok) {
        ui.btnFont->setFont(f);
    };
};

void ConfigWindow::showColorPicker() {
    QWidget* widget = qobject_cast<QWidget*>(sender());
    //qAssert(widget);
    QPalette palette = widget->palette();
    QColor c = palette.color(QPalette::Button);
    c = QColorDialog::getColor(c, this);
    if (c.isValid()) {
        palette.setColor(QPalette::Button, c);
        widget->setPalette(palette);
    };
};

void ConfigWindow::selectLyricsEditor() {
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::ExistingFile);
    if (dialog.exec()) {
        ui.txtLyricsEditor->setText(dialog.selectedFiles().first());
    };
};

void ConfigWindow::showDownloadDir() {
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::DirectoryOnly);
    if (dialog.exec()) {
        ui.txtDownloadDir->setText(dialog.selectedFiles().first());
    };
};

void ConfigWindow::slotDownloadDirChanged(bool) {
    if (ui.rbnSongDirectory->isChecked()) {
        ui.txtDownloadDir->setEnabled(false);
        ui.pbnDownloadDir->setEnabled(false);
        ui.txtDownloadDir->setText(QString());
    } else {
        ui.txtDownloadDir->setEnabled(true);
        ui.pbnDownloadDir->setEnabled(true);
    };
};

void ConfigWindow::addSearchDir() {
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::DirectoryOnly);
    if (dialog.exec()) {
        m_lyricsFolders.insertRow(m_lyricsFolders.rowCount());
        m_lyricsFolders.setData(m_lyricsFolders.index(m_lyricsFolders.rowCount() - 1, 0),
            dialog.selectedFiles().first());
    };
};

void ConfigWindow::removeSearchDir() {
    m_lyricsFolders.removeRow(ui.lsvSearchPath->currentIndex().row());
};

